from typing import Dict, Any, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from core.pagination import paging_data, _CustomPageParams
from fastapi import HTTPException, status

from modules.case_qc.models.case_qc_model import CaseQc
from modules.case_qc.schemas.case_qc_schema import CaseQcCreate, CaseQcUpdate
from modules.case_qc.params.case_qc_params import CaseQcQuery
from modules.case_qc.curd.case_qc_curd import case_qc_dao
from utils.query_builder import build_select_stmt


class CaseQcService:
    @staticmethod
    async def get_list_with_pagination(db: AsyncSession, query_params: CaseQcQuery) -> Dict[str, Any]:
        stmt = build_select_stmt(
            CaseQc,
            query_params,
            order_by_desc="id",
            text_like_fields=None,
        )
        params = _CustomPageParams(page=query_params.page, size=query_params.size)
        return await paging_data(db, stmt, params=params)

    @staticmethod
    async def get_by_id(db: AsyncSession, pk: Any) -> Optional[CaseQc]:
        repo = await case_qc_dao.get_by_id(db, pk)
        return repo

    @staticmethod
    async def create(db: AsyncSession, data: CaseQcCreate) -> CaseQc:
        repo = await case_qc_dao.create(db, data)
        await db.commit()
        await db.refresh(repo)
        return repo

    @staticmethod
    async def update(db: AsyncSession, pk: Any, data: CaseQcUpdate) -> Optional[CaseQc]:
        # DAO 返回 ORM 实例，避免 UnmappedInstanceError
        repo = await case_qc_dao.update(db, pk, data)
        if not repo:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"记录 {pk} 不存在")
        await db.commit()
        await db.refresh(repo)
        return repo

    @staticmethod
    async def delete(db: AsyncSession, pk: Any) -> bool:
        repo = await case_qc_dao.delete(db, pk)
        if not repo:
            return False
        await db.commit()
        return True